﻿/**************************************************************
 *
 * 唯一标识：93de1631-661c-4c84-b470-498d43267416
 * 命名空间：Sgr.IntegrationEvents
 * 创建时间：2023/8/19 21:13:34
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：
 *
 **************************************************************/

using Microsoft.Extensions.DependencyInjection.Extensions;
using Sgr.Modules;
using Sgr.Oss.Apis;
using Sgr.Security.Permissions;
using System.Threading.RateLimiting;

namespace Sgr.Oss
{
    public class ModuleStartup : ModuleStartupBase
    {
        public override int Order => 100;

        /// <summary>
        /// 配置终结点路由
        /// </summary>
        /// <param name="endpoints">终结点路由构建器</param>
        public override void ConfigureEndpoints(IEndpointRouteBuilder endpoints)
        {
            // 注册OSS终结点
            endpoints.MapOssEndpoints();
        }

        /// <summary>
        /// 模块服务初始化
        /// </summary>
        /// <param name="services"></param>
        public override void ConfigureServices(IServiceCollection services)
        {
            services.TryAddEnumerable(ServiceDescriptor.Singleton<IPermissionProvider, Permissions>());

            // 注册本地文件系统OSS服务
            services.AddLocalFilesystemOssService();

            // 添加限流服务配置
            services.AddRateLimiter(options =>
            {
                // 添加针对Oss服务的限流策略
                options.AddPolicy("RateLimiterPolicy.Sgr.Oss", httpContext =>
                    RateLimitPartition.GetFixedWindowLimiter(
                        partitionKey: httpContext.GetClientIpAddress(),
                        factory: partition => new FixedWindowRateLimiterOptions
                        {
                            AutoReplenishment = true,
                            PermitLimit = 100,                  // 允许的请求数
                            QueueLimit = 0,                     // 队列限制
                            Window = TimeSpan.FromMinutes(1)    // 时间窗口
                        }));
            });
        }
    }
}